<template>
  <div class="p-16px">
    <el-card>
      <el-space wrap :size="16">
        <div class="flex items-center whitespace-nowrap">
          代理名称：
          <el-input
            placeholder="请输入内容"
            v-model="params.name"
            clearable
          ></el-input>
        </div>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" plain @click="handleAdd">添加</el-button>
      </el-space>
    </el-card>
    <el-card class="mt-16px">
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="编号" width="80" />
        <el-table-column prop="name" label="代理名称" min-width="180" />
        <el-table-column prop="employeeName" label="联系人" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="180" />
        <el-table-column
          prop="lastLoginTime"
          label="最近登录时间"
          min-width="180"
        />
        <el-table-column
          prop="createTime"
          label="操作"
          width="280"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              plain
              @click="handleShowAssignDevice(scope.row)"
            >
              分配设备
            </el-button>
            <el-button type="primary">编辑</el-button>
            <el-button type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-16px flex justify-end">
        <el-pagination
          v-model:currentPage="params.current"
          v-model:page-size="params.size"
          layout="prev, pager, next"
          background
          :total="total"
          @current-change="fetchList"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="isShowDialog"
      :title="form.id ? '编辑代理' : '新建代理'"
    >
      <el-form label-width="80px">
        <el-form-item label="代理名称">
          <el-input v-model="form.name" placeholder="请输入代理名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input
            v-model="form.employeeName"
            placeholder="请输入联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input
            v-model="form.phone"
            placeholder="请输入联系方式"
          ></el-input>
          <p class="mb-0 mt-0 text-12px text-gray-500">密码和联系方式相同</p>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <DistributorRole v-model="form.roleIds" />
        </el-form-item>
        <el-form-item label="开启分润">
          <el-switch
            v-model="form.profitStatus"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="分润比例" v-if="form.profitStatus">
          <el-input-number v-model="form.profitRatio" :min="0" :max="100">
            <template #suffix>
              <span>%</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            提交
          </el-button>
          <el-button @click="isShowDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="分配设备" v-model="isShowDeviceDialog">
      <el-space>
        <span>设备编号：</span>
        <el-input
          v-model="deviceParams.deviceCode"
          placeholder="请输入设备编号"
        ></el-input>
        <el-button type="primary" @click="handleSearchDevice">搜索</el-button>
      </el-space>
      <el-divider />
      <el-space>
        <span>已选设备：</span>
        <el-tag
          v-for="item in selectedDeviceList"
          :key="item.id"
          type="primary"
          closable
        >
          {{ item.deviceCode }}
        </el-tag>
      </el-space>
      <el-divider />
      <el-table :data="deviceList" style="width: 100%">
        <el-table-column type="index" label="#" width="80px" />
        <el-table-column prop="deviceCode" label="设备编号" />
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="deviceType" label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleAssignDevice(scope.row)">
              添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-16px flex justify-end">
        <el-pagination
          v-model:currentPage="deviceParams.current"
          v-model:page-size="deviceParams.size"
          layout="prev, pager, next"
          background
          :total="deviceParams.total"
          @current-change="fetchDeviceList"
        />
      </div>
      <div class="mt-16px flex justify-center">
        <el-button
          type="primary"
          @click="handleAssignDeviceSubmit"
          :loading="submitLoading"
        >
          确认分配
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useCommonStoreHook } from "@/store/modules/common";
import DistributorRole from "@/components/Select/DistributorRole.vue";
import dayjs from "dayjs";
const commonStore = useCommonStoreHook();
const params = ref({
  name: "",
  size: 10,
  current: 1,
});
const deviceParams = ref({
  deviceCode: "",
  size: 10,
  current: 1,
  total: 0,
});
const isShowDialog = ref(false);
const isShowDeviceDialog = ref(false);
const tableData = ref([]);
const loading = ref(false);
const defaultForm = {
  name: "",
  employeeName: "",
  phone: "",
  profitStatus: 0,
  profitRatio: 0,
  roleIds: [],
};
const form = ref({ ...defaultForm });
const selectedDeviceList = ref([]);
const deviceList = ref([]);
const total = ref(0);
const submitLoading = ref(false);
const selectedRow = ref({});

const handleSearchDevice = () => {
  deviceParams.value.current = 1;
  fetchDeviceList();
};
const fetchDeviceList = () => {
  commonStore
    .getDeviceInfoPage(deviceParams.value)
    .then((res: any) => {
      deviceList.value = res.records;
      deviceParams.value.total = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleShowAssignDevice = (row: any) => {
  selectedRow.value = row;
  handleSearchDevice();
  isShowDeviceDialog.value = true;
};
const handleSubmit = () => {
  submitLoading.value = true;
  commonStore
    .saveDistributorInfo({
      ...form.value,
    })
    .then((res) => {
      handleSearch();
      isShowDialog.value = false;
    })
    .finally(() => {
      submitLoading.value = false;
    });
};
const handleAssignDevice = (row: any) => {
  const index = selectedDeviceList.value.findIndex(
    (item: any) => item.id === row.id
  );
  if (index === -1) {
    selectedDeviceList.value.push(row);
  } else {
    ElMessage.error("设备已存在");
  }
};

const handleAssignDeviceSubmit = () => {
  submitLoading.value = true;
  commonStore
    .bindDeviceEmployeeRel({
      deviceCode: selectedDeviceList.value
        .map((item: any) => item.deviceCode)
        .join(","),
      employeeId: selectedRow.value.id,
    })
    .then((res) => {
      ElMessage.success("分配成功");
      isShowDeviceDialog.value = false;
      handleSearch();
    })
    .finally(() => {
      submitLoading.value = false;
    });
};

const handleAdd = () => {
  isShowDialog.value = true;
};

const handleSearch = () => {
  params.value.current = 1;
  fetchList();
};

const fetchList = () => {
  loading.value = true;
  commonStore
    .queryDistributorInfoPage({
      current: params.value.current,
      size: params.value.size,
    })
    .then((res: any) => {
      tableData.value = res.records.map((item) => ({
        ...item,
        createTime: dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss"),
        lastLoginTime: dayjs(item.lastLoginTime).format("YYYY-MM-DD HH:mm:ss"),
      }));
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped></style>
